import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = [
  'home',
  'signup',
  'signin',
  'news-list',
  'news-detail',
  'project-list',
  'project-detail',
  'yuanqu-list',
  'yuanqu-detail',
  'project-docking',
  'project-docking-detail',
  'project-list',
  'disclaimer',
  'about',
  'UserAgreementView',
  'ProductAndServiceView',
  'CollectView',
  'ConformView',
  'FriendView',
  'UnionView',
  'ForwordView',
  'SingnCode'
] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
    // console.log(www.baidu.com);
    window.location.href = "http://1stzone.cn/mobileweb/";
    return;
  }
  // start progress bar
  NProgress.start()
  
  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/signin') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      await store.dispatch('user/getInfo')
      next()
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.name) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/signin?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
